package gostrings

import "strings"

// Tokenizer 占位符解析器
type Tokenizer struct {
	Prefix string
	Subbix string
	DefVal string
}

// 默认占位符解析器
var defaultTokenizer = &Tokenizer{
	Prefix: DELIM_START + DELIM_START,
	Subbix: DELIM_END + DELIM_END,
	DefVal: COLON,
}

// ReplacePlaceholders 替换占位符
// value 待替换的字符串
// parameters 占位符参数
func ReplacePlaceholders(value string, parameters map[string]string) string {
	// NewTokenizer
	return ReplacePlaceholdersTokenizer(value, defaultTokenizer, func(name string) string {
		return parameters[name]
	})
}

// ReplacePlaceholdersTokenizer 替换占位符
// value 待替换的字符串
// tokenizer 占位符解析器
// fun 解析函数
func ReplacePlaceholdersTokenizer(value string, tokenizer *Tokenizer, fun func(name string) string) string {
	// NewTokenizer
	builder := &strings.Builder{}
	for true {
		index1 := strings.Index(value, tokenizer.Prefix)
		if index1 < 0 {
			builder.WriteString(value)
			return builder.String()
		} else {
			builder.WriteString(value[:index1])
			value = value[index1:]
		}
		index2 := strings.Index(value, tokenizer.Subbix)
		if index2 < 0 {
			builder.WriteString(value)
			return builder.String()
		}
		def := ""
		sub := value[len(tokenizer.Prefix):index2]
		index3 := strings.Index(sub, tokenizer.DefVal)
		if index3 > 0 {
			def = sub[index3+1:]
			sub = sub[:index3]
		}
		val := fun(strings.TrimSpace(sub))
		if val != "" {
			builder.WriteString(strings.TrimSpace(val))
		} else if index3 > 0 {
			builder.WriteString(strings.TrimSpace(def))
		} else {
			builder.WriteString(value[:index2+len(tokenizer.Subbix)])
		}
		value = value[index2+len(tokenizer.Subbix):]
	}
	return builder.String()
}
